<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    :label-width="options.labelWidth"
  >
    <el-row>
      <el-col
        :span="options.span"
        v-for="(item, index) in options.list"
        :key="index"
      >
        <el-form-item
          :label="item.label"
          :prop="item.prop"
          v-if="!(item.label === '密码' && edit)"
        >
          <!-- 文本框、数字框、下拉框、日期框、开关、上传 -->
          <el-input
            v-if="item.type === 'input'"
            v-model="form[item.prop]"
            :disabled="item.disabled"
            :placeholder="item.placeholder"
            clearable
          ></el-input>
          <el-input-number
            v-else-if="item.type === 'number'"
            v-model="form[item.prop]"
            :disabled="item.disabled"
            controls-position="right"
          ></el-input-number>
          <el-select
            v-else-if="item.type === 'select'"
            v-model="form[item.prop]"
            :multiple="item.multiple"
            :disabled="item.disabled"
            :placeholder="item.placeholder"
            clearable
          >
            <el-option
              v-for="(opt, index) in item.opts"
              :label="opt.label"
              :value="opt.value"
              :key="index"
            ></el-option>
          </el-select>
          <el-date-picker
            v-else-if="item.type === 'date'"
            type="date"
            v-model="form[item.prop]"
            :value-format="item.format"
          ></el-date-picker>
          <el-switch
            v-else-if="item.type === 'switch'"
            v-model="form[item.prop]"
            :active-value="item.activeValue"
            :inactive-value="item.inactiveValue"
            :active-text="item.activeText"
            :inactive-text="item.inactiveText"
          ></el-switch>
          <el-upload
            v-else-if="item.type === 'upload'"
            class="avatar-uploader"
            action="http://129.204.225.193:8890/web/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            accept=".jpg,.jpeg,.png,.gif"
            :before-upload="handleBeforeUpload"
          >
            <div
              v-if="form[item.prop] && form[item.prop].indexOf('http') !== -1"
            >
              <div
                :style="{ backgroundImage: 'url(' + form[item.prop] + ')' }"
                class="avatar"
              ></div>
            </div>
            <div
              v-if="form[item.prop] && form[item.prop].indexOf('http') !== -1"
              class="tishitu"
            >
              (点击图片进行替换)
            </div>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
          <el-upload
            v-else-if="item.type === 'uploadSong'"
            action="http://129.204.225.193:8890/web/file/upload"
            :on-success="handleMusicSuccess"
            :limit="1"
            :on-remove="handleRemove"
            accept=".mp3,.wav,.flac"
            :before-upload="handleBeforeUpload2"
          >
            <div v-if="form[item.prop]">
              <a
                :href="form[item.prop]"
                target="_blank"
                v-if="form[item.prop] && form[item.prop].indexOf('http') !== -1"
                >{{ form[item.prop] }}</a
              >
              <span v-else class="redTishi"
                >音频文件地址有误，请重新上传正确的地址</span
              >
            </div>
            <template #trigger>
              <el-button type="primary">上传音乐</el-button>
            </template>
          </el-upload>
          <el-upload
            v-else-if="item.type === 'uploadLyric'"
            action="http://129.204.225.193:8890/web/file/upload"
            :on-success="handleLyricSuccess"
            :limit="1"
            accept=".txt"
            :on-remove="handleRemove2"
            :before-upload="handleBeforeUpload3"
          >
            <div v-if="form[item.prop]">
              <a :href="form[item.prop]" target="_blank">{{
                form[item.prop]
              }}</a>
            </div>
            <template #trigger>
              <el-button type="primary">上传歌词</el-button>
            </template>
            <template #tip>
              <div v-if="!form[item.prop]" class="el-upload__tip">
                请上传.txt的文件
              </div>
            </template>
          </el-upload>
          <slot :name="item.prop" v-else> </slot>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item class="dibuAan">
      <el-button @click="closeDialogPra">取 消</el-button>
      <el-button type="primary" @click="saveEdit(formRef)">确 定</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { FormOption } from "@/types/form-option";
import { FormInstance, FormRules, UploadProps } from "element-plus";
import { PropType, ref } from "vue";
import { ElMessage } from "element-plus";
const emit = defineEmits(["closeDialogP"]);

const closeDialogPra = () => {
  emit("closeDialogP");
};

const { options, formData, edit, update } = defineProps({
  options: {
    type: Object as PropType<FormOption>,
    required: true,
  },
  formData: {
    type: Object,
    required: true,
  },
  edit: {
    type: Boolean,
    required: false,
  },
  update: {
    type: Function,
    required: true,
  },
});

const form = ref({ ...(edit ? formData : formData) });

const rules: FormRules = options.list
  .map((item) => {
    if (item.required) {
      return {
        [item.prop]: [
          { required: true, message: `${item.label}不能为空`, trigger: "blur" },
        ],
      };
    }
    return {};
  })
  .reduce((acc, cur) => ({ ...acc, ...cur }), {});

const formRef = ref<FormInstance>();
const saveEdit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (!valid) return;
    console.log("ces测试");
    console.log(form.value);
    update(form.value);
  });
};

// 上传前验证格式（图片）
const handleBeforeUpload = (file) => {
  const isJPGOrPNG =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/gif" ||
    file.type === "image/jpg";
  if (!isJPGOrPNG) {
    ElMessage.error("只能上传png,jpg,gif等格式的图片!");
    return false; // 阻止文件上传
  }
  return true; // 允许文件上传
};

// 上传前验证格式（音乐 .mp3）
const handleBeforeUpload2 = (file) => {
  console.log("音乐");
  console.log(file);
  const isJPGOrPNG =
    file.type === "audio/mpeg" ||
    file.type === "audio/wav" ||
    file.type === "audio/mp3" ||
    file.type === "audio/flac";
  if (!isJPGOrPNG) {
    ElMessage.error("只能上传音频格式的音乐!");
    return false; // 阻止文件上传
  }
  return true; // 允许文件上传
};

// 上传前验证格式（歌词 .txt）
const handleBeforeUpload3 = (file) => {
  console.log("歌词");
  console.log(file);
  const isJPGOrPNG = file.type === "text/plain";
  if (!isJPGOrPNG) {
    ElMessage.error("只能上传.txt格式的文件!");
    return false; // 阻止文件上传
  }
  return true; // 允许文件上传
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log("上传图片后---返回结果");
  console.log(response);
  form.value.coverUrl = response.data.fileUrl;
};
// 上传音乐
const handleMusicSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  console.log("上传音乐后---返回结果");
  console.log(response);
  form.value.songFileUrl = response.data.fileUrl;
  console.log(form.value.songFileUrl);
};

// 删除音乐
const handleRemove = (fileName, fileList, index) => {
  console.log("删除音乐");
  console.log(fileName);
  console.log(fileList);
  console.log(index);
  form.value.songFileUrl = "";
};

// 上传歌词
const handleLyricSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  console.log("上传歌词后---返回结果");
  console.log(response);
  form.value.lyricFileUrl = response.data.fileUrl;
  console.log(form.value.lyricFileUrl);
};

// 删除歌词
const handleRemove2 = (fileName, fileList, index) => {
  console.log("删除歌词");
  form.value.lyricFileUrl = "";
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .el-upload {
  width: 200px;
  height: 200px;
  display: block;
  overflow: visible;
}
.avatar {
  width: 200px;
  height: 200px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  /* border: 1px dashed var(--el-border-color); */
}
.el-select {
  /* width: 200px; */
  min-width: 200px;
}
.el-cascader {
  width: 100%;
}
.tishitu {
  position: relative;
  /* top: 30px; */
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  margin: 0 auto;
  text-align: center;
  display: block;
  line-height: 200px;
}
.el-row {
  margin-bottom: 20px;
}
.dibuAan .el-form-item__content {
  justify-content: right;
  border-top: 1px solid #efefef;
  padding: 0 20px;
  box-sizing: border-box;
  padding-top: 20px;
  width: 100%;
  margin-left: 0 !important;
}
.el-dialog {
  padding: 0;
}
.el-dialog__header {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #efefef;
  margin-bottom: 20px;
  box-sizing: border-box;
}
.el-row {
  padding: 0 20px;
  box-sizing: border-box;
}
.el-dialog__headerbtn {
  top: 10px;
}
</style>
